#pragma once
#include "Socket.hpp"
#include <memory>
#include <sys/wait.h>
#include<functional>

using serverio = std::function<void(std::shared_ptr<Socket>& sock,InetAddr& client)>;

class Tcpserver
{
private:
public:
    Tcpserver(uint16_t port,serverio service)
        : _port(port),
          _listensockptr(std::make_unique<TcpSocket>()),
          _isruning(false),
          _service(service)
    {
        _listensockptr->BuildTcpSocketServer(port);
    }

    void Start()
    {
        _isruning = true;
        while (_isruning)
        {
            // 建立连接
            InetAddr addr;
            auto sock = _listensockptr->Accept(&addr);
            if (sock == nullptr)
                continue;
            LOG(LogLevel::DEBUG) << addr.GetName()<<"accept success ...";

            pid_t id = fork();
            if (id < 0)
            {
                LOG(LogLevel::FATAL) << "fork error";
                exit(FORK_ERR);
            }
            else if (id == 0)
            {
                // 关闭监听文件
                _listensockptr->Close();
                if (fork() > 0) // 将子进程退出
                    exit(OK);
                // 孙子进程执行任务
                _service(sock, addr);
                sock->Close();
                exit(OK);
            }
            else
            {
                sock->Close();
                pid_t pid = waitpid(id, nullptr, 0);
            }
        }
        _isruning = false;
    }
    ~Tcpserver()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensockptr;
    bool _isruning;
    serverio _service;
};